import React, { useState, useEffect, useCallback } from 'react';
import { WifiOutlined } from '@ant-design/icons';
import './index.scss';



const useNetworkStatus = (callback) => {
  const handleOnline = () => callback(true);
  const handleOffline = () => callback(false);

  useEffect(() => {
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    
    callback(navigator.onLine);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, [callback]);
};

const NetworkStatus = ({ retryable = true, customMessage = '' }) => {
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  const [retrying, setRetrying] = useState(false);

  const handleNetworkChange = useCallback((online) => {
    setIsOnline(online);
    
    
    
  }, []);

  useNetworkStatus(handleNetworkChange);

  const message = retrying
    ? '正在重新连接...'
    : customMessage || (isOnline ? '网络已连接' : '网络连接已断开');

  const handleRetry = async () => {
    setRetrying(true);
    try {
      
      await fetch(window.location.origin + '/ping');
      setIsOnline(true);
    } catch (error) {
      console.error('Network retry failed:', error);
    } finally {
      setRetrying(false);
    }
  };

  return (
    <div className={`network-status ${!isOnline ? 'is-offline' : ''}`}>
      {/* 在 React 中实现 Vue 的 <transition> 效果通常需要使用第三方库，
        如 react-transition-group。这里仅通过 CSS 类名控制显隐和简单的过渡。
      */}
      {!isOnline && (
        <div className="offline-banner">
          <span className="icon">
            <WifiOutlined />
          </span>
          <span className="message">{message}</span>
          {retryable && (
            <button onClick={handleRetry} className="retry-button">
              重试
            </button>
          )}
        </div>
      )}
    </div>
  );
};

export default NetworkStatus;